/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package javagprssrv.DataBase;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import javagprssrv.JGS_Param;
import org.apache.log4j.Logger;

/**
 *
 * @author dusin
 */
public class Insert5mThread extends Thread{
    StringBuilder sb = new StringBuilder();
    Logger logger = Logger.getLogger(Insert5mThread.class);
    DBSQLExecute dbse = new DBSQLExecute();
    private static final int BATCH_SIZE=10;   //批处理的最大值
    private static final int FLAG_SIZE=50000; //需要同时在标记集合中的记录数
    List<Object[]> createList = new ArrayList<>();

    public Insert5mThread() {
        super("Insert5mThread");
    }
    
    @Override
    public  void run(){
        while(true){
            try {
                Thread.sleep(20L);
            } catch (InterruptedException ex) {
                
            }
            int count=0;
            Object[] bean=null;
            //最多取出BATCH_SIZE条记录
            while(count<=BATCH_SIZE&&(bean=JGS_Param.queueFor5m.poll())!=null){   //取出队列中的元素准备插入
                sb.append(bean[1]).append(bean[2]);
                if(!JGS_Param.flagSetFor5m.contains(sb.toString())){   //如果该5分钟数据没有插入过，则追加到插入列表。
                    createList.add(bean);
                    count++;
                    JGS_Param.flagSetFor5m.add(sb.toString());
                }
                sb.delete(0, sb.length());                
            }            
            try{
                count=0;
                if(!createList.isEmpty()){
                    dbse.doCreateBatch(createList);                    
                    logger.info("成功插入"+createList.size()+"条5m钟数据");                    
                    createList.clear();
                }else{
                    continue;
                }
            }catch(Exception e){  //因一条数据原因，导致整批数据无法插入。所以转逐条插入队列，以尽可能多的插入数据
                logger.info("同时插入"+createList.size()+"条5m钟数据失败,将放入逐条插入队列"+e.getMessage());
                if(createList.size()>1){
                    JGS_Param.queueForEach5m.addAll(createList);
                }
                createList.clear();
            }            
            Iterator it = JGS_Param.flagSetFor5m.iterator();
            while(it.hasNext()&&JGS_Param.flagSetFor5m.size()>FLAG_SIZE){
                it.next();
                it.remove();
            }
        }
    }
}
